#%%

import pandas as pd
import os
import flask
import json
import config

#%%




g_assignments = []
g_grade_sheet = {} # 是一个字典


#%%

app = flask.Flask(__name__, static_folder=config.ROOT_PATH)

#%%
def parseFileName(filename : str):
    d = {}
    d['学号'] = filename.split('-')[0]
    d['姓名'] = filename.split('-')[1]
    return d


#%%

@app.route('/assignments/next', methods=['GET'])
def getNextAssignmets():
    all_problems_num = flask.request.args.get('all_problems_num')
    wrong_answer_num = flask.request.args.get('wrong_answer_num')
    filename = flask.request.args.get('filename')
    if filename != '':
        all_problems_num = float(all_problems_num)
        wrong_answer_num = float(wrong_answer_num)
        d = parseFileName(filename)
        global g_grade_sheet
        g_grade_sheet[d['学号']] = int((1-wrong_answer_num/all_problems_num)*100)
        g_assignments.remove(filename)

    data = {}
    if len(g_assignments) > 0:
        data['filename'] = g_assignments[0]
    else:
        data['filename'] = ''

    return json.JSONEncoder().encode(data)
    

#%%

@app.route('/assignments/<filename>', methods=['GET'])
def showAssignments(filename):
    return flask.send_from_directory(config.ASSIGNMETS_DIR,  filename)
    # with open('pages/showPDF.html') as f:
    #     return f.read()

#%%

@app.route('/', methods=['GET'])
def index():
    # html_content = "<h1>欢迎来到作业批改系统</h1>"
    # if len(assignments) == 0:
    #     html_content += "没有作业需要批改"
    # else:
    #     html_content += '<a href="/pdf/%s">点击该链接开始批改作业</a>' % assignments[1]
    # return html_content
    with open('pages/index.html', encoding='utf-8') as f:
        s = f.read()
    # s = s.format(assignments[0])
    return s

#%%

def readGradeSheet():
    grade_sheet = None
    if os.path.exists(config.GRADE_SHEET_PATH):
        grade_sheet = pd.read_csv(config.GRADE_SHEET_PATH)
    else:
        grade_sheet = pd.DataFrame(columns=['学号', '成绩'])
    grade_sheet.to_dict('list')
    d = {}
    for i in range(len(grade_sheet['学号'])):
        d[str(grade_sheet['学号'][i])] = grade_sheet['成绩'][i]
    return d

#%%
def readAssignmentsFileName():
    global g_assignments
    global g_grade_sheet
    assignments = os.listdir(config.ASSIGNMETS_DIR)
    try:
        assignments.remove(config.GRADE_SHEET_FILE_NAME)
    except:
        pass
    
    if g_grade_sheet is None:
        g_grade_sheet = readGradeSheet()
    else:
        for i in assignments:
            student_number = i.split('-')[0]
            if g_grade_sheet.get(student_number) is None:
                g_assignments.append(i)
    return

#%%
def saveGrade2Sheet():
    global g_grade_sheet

    # traceback.print_stack()

    # 不明白为什么这个函数被执行了多次，只能通过判断只写入一次
    if (g_grade_sheet is not None) and (len(g_grade_sheet) > 0):
        print('runAtExit')
        print(g_grade_sheet)
        grade_sheet = pd.DataFrame(g_grade_sheet.items(), columns=['学号', '成绩'])
        grade_sheet.to_csv(config.GRADE_SHEET_PATH, index=False, encoding='utf-8')
        g_grade_sheet.clear()
        g_grade_sheet = None
        print('****************************************')

    return

#%%

if __name__ == '__main__':
    g_grade_sheet = readGradeSheet()
    readAssignmentsFileName()
    app.run(host='127.0.0.1', port=5000, debug=False)
    saveGrade2Sheet() # CTRL+C退出时会调用该函数，在 app.run debug=True时该函数会被执行两次，不理解为什么

#%%

